<?php
/**
 * 验证
 */

namespace Common\Controller\App;

use Common\Model\CouponModel;
use Common\Model\MemberMessageModel;
use Common\Model\MemberModel;
use Common\Model\MemberWeixinModel;
use Think\Controller;
use Think\Wxpay\Wxpay;

class SignController extends Controller
{

    static public $shop_id;
    static public $server_url;

    public function __construct()
    {

        parent::__construct();

        $this->is_shop();
        $this->is_weixin();

    }
    /**
     * 检查是否有店铺id
     */
    public function is_shop()
    {
        $shop_id = I('param.shop_id');
        if(empty($shop_id)){
            $shop_id = 0;
        }

        self::$shop_id = $shop_id;
        $member_id = session('member_id');
        if(empty($member_id)){
            $token = I('post.token');
            if(!empty($token)){
                $id = authcode($token,'DECODE');
                if($id){
                    $t_model = new MemberModel();
                    $member_info = $t_model->where("member_id=$id")->find();
                    if(empty($member_info)){
                        $this->ajaxReturn(['code'=>301,'msg'=>'token错误']);
                    }
                    session('member_id',$id);
                }
            }

        }
    }

    /**
     * 判断是否是微信浏览器
     * @return bool
     */
    public function is_weixin(){

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {

            $this->weixin();
        }
    }

    /**
     * 获取微信信息
     */

    public function weixin(){
        $shop_id = self::$shop_id;
        $code            = I('param.code');
        $member_id       = session('member_id');
        self::$server_url= $_SERVER;

        if(empty($member_id)){
            if(empty($code)){
                $url = "http://www.honeybee2015.com/App/Index/Index/wxlogin?shop_id=".$shop_id;
                $url = urlencode($url);
                if(empty($member_id)  && empty($code)){
                    header("location:http://open.weixin.qq.com/connect/oauth2/authorize?appid=wx09632c5caa1f84d8&redirect_uri=$url&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                }
                $this->ajaxReturn(['code'=>301,'msg'=>'缺少用户code信息']);
            }
        }
        $wx      = new Wxpay();
        $wxinfo  = $wx->getUserInfo($code);
        $unionid = $wxinfo['userinfo']['openid'];
        $model   = new MemberModel();;
        $m_model = new MemberWeixinModel();

        if($unionid){
            //获取微信用户信息
            $memberotherinfo = $m_model->where("unique_code='$unionid'")->field("member_id,unique_code")->find();
            if($memberotherinfo){
                $userid = $memberotherinfo['member_id'];
                session('member_id',$userid);
                if(empty($userid)){
                    $m_model->where("open_secretid='$unionid'")->delete();
                    $this->reg($wxinfo,$shop_id);
                }
                $model->upload($userid,$wxinfo['userinfo']['headimgurl']);
                $model->where("id='$userid'")->save(['login_time'=>date('Y-m-d H:i:s',time())]);
            }else{
                $this->reg($wxinfo,$shop_id);
            }
        }
    }

    /**
     * 注册
     * @param $type
     * @param $wxinfo          微信信息
     * @param $localhost_url   请求url
     */

    public function reg($wxinfo,$shop_id){
        $model = M();
        $model->startTrans();
        $data['name'] = $this->emoji_encode($wxinfo['userinfo']['nickname']);
        $data['login_time'] = date('Y-m-d H:i:s',time());
        $data['parent_id'] = $shop_id;
        $data['sex'] = $wxinfo['userinfo']['sex'];
        $data['logo']   = $wxinfo['userinfo']['headimgurl'];
        $data['create_time'] = date('Y-m-d H:i:s',time());
        $m_id = $model->table(C('DB_PREFIX').'member')->add($data);

        $w_data['unique_code'] = $wxinfo['userinfo']['openid'];
        $w_data['member_id'] = $m_id;
        $w_data['data'] = json_encode($wxinfo);
        $w_data['create_time'] = date('Y-m-d H:i:s',time());
        $w_id = $model->table(C('DB_PREFIX').'member_weixin')->add($w_data);
        if($m_id && $w_id){
            $pmodel = new CouponModel();
            $pmodel->add(['member_id'=>$m_id,'title'=>'新人代金券','money'=>100,'type'=>1,'start_time'=>date('Y-m-d H:i:s',time()),'end_time'=>date("Y-m-d H:i:s",strtotime("+1 month")),'create_time'=>date('Y-m-d H:i:s',time())]);
            $pmodel->add(['member_id'=>$m_id,'title'=>'新人代金券','money'=>100,'type'=>0,'start_time'=>date('Y-m-d H:i:s',time()),'end_time'=>date("Y-m-d H:i:s",strtotime("+1 month")),'create_time'=>date('Y-m-d H:i:s',time())]);
            $model->commit();
            session('member_id',$m_id);
            if($shop_id){
                $model = new MemberMessageModel();
                $model->add(['member_id'=>$shop_id,'content'=>$wxinfo['userinfo']['nickname']."通过你的邀请成为你的粉丝",'create_time'=>date('Y-m-d H:i:s',time())]);
            }
        }else{
            $model->rollback();
        }

    }
    private function emoji_encode($nickname){
        $strEncode = '';
        $length = mb_strlen($nickname,'utf-8');
        for ($i=0; $i < $length; $i++) {
            $_tmpStr = mb_substr($nickname,$i,1,'utf-8');
            if(strlen($_tmpStr) >= 4){
                //$strEncode .= '[[EMOJI:'.rawurlencode($_tmpStr).']]';
            }else{
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
     }
}
